﻿@page "/module/{Module}/{Target}/{Id?}"

@using Gurux.DLMS.AMI.Shared.DIs

@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Gurux.DLMS.AMI.Shared.DTOs
@using Gurux.DLMS.AMI.Shared.Rest
@using Gurux.DLMS.AMI.Shared.Enums
@using System.IO
@using Gurux.DLMS.AMI.Module
@using System.Linq
@using System.Net.Http.Headers
@using System.Text.Json
@using Microsoft.Extensions.Logging
@using Microsoft.Extensions.Options


@inject GXModuleService modules
@inject NavigationManager NavigationManager
@inject HttpClient Http
@inject IGXNotifier Notifier
@inject ILogger<ModuleView> Logger
@inject GXModuleService modules
@implements IDisposable

@if (_configurationUI != null)
{
    RenderFragment renderFragment = (builder) =>
    {
        builder.OpenComponent(0, _configurationUI);
        @if (_moduleSettings != null)
        {
            builder.AddAttribute(1, "Settings", _moduleSettings);
        }
        builder.AddComponentReferenceCapture(0, inst => { _module = (IAmiModuleSettings)inst; });
        builder.CloseComponent();
    };
    <div>
        @renderFragment
    </div>
}

@code {

    /// <summary>
    /// Target module.
    /// </summary>
    [Parameter]
    public string? Module { get; set; }

    /// <summary>
    /// Module action.
    /// </summary>
    [Parameter]
    public string? Target { get; set; }

    /// <summary>
    /// Module target ID.
    /// </summary>
    [Parameter]
    public string? Id { get; set; }

    private Type? _configurationUI;
    private IAmiModuleSettings? _module = null;
    object? _moduleSettings;
    bool initialized;

    protected override void OnInitialized()
    {
        try
        {
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            Notifier.Clear();
            if (string.IsNullOrEmpty(this.Module) || string.IsNullOrEmpty(Target))
            {
                NavigationManager.NavigateTo("404");
            }
            foreach (var asm in modules.Assemblies)
            {
                foreach (var type in asm.GetExportedTypes())
                {
                    if (type.IsAbstract || !type.IsClass || type.FullName == null)
                    {
                        continue;
                    }
                    if (type.GetInterfaces().Contains(typeof(IAmiModule)))
                    {
                        IAmiModule? tmp = (IAmiModule?)asm.CreateInstance(type.FullName);
                        if (string.Compare(Target, tmp?.Id, true) != 0)
                        {
                            break;
                        }
                    }
                    else if (type.GetInterfaces().Contains(typeof(IAMINavigation)))
                    {
                        IAMINavigation? tmp = (IAMINavigation?)asm.CreateInstance(type.FullName);
                        if (tmp?.NavItems != null && tmp.NavItems.Any())
                        {
                            foreach (var it in tmp.NavItems)
                            {
                                if (string.Compare(Target, it.Component?.Name) == 0)
                                {
                                    _configurationUI = it.Component;
                                    break;
                                }
                            }
                        }
                    }
                }
                if (_configurationUI != null)
                {
                    break;
                }
            }
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    protected override void OnAfterRender(bool firstRender)
    {
        if (!initialized && _module != null)
        {
            //Set module settings.
            initialized = true;
            _module.Initialize();
        }
        else if (_module != null && initialized)
        {
            //Get module settings if UI is updated.
            _moduleSettings = null;
            var settings = _module.GetType().GetProperty("Settings");
            if (settings != null)
            {
                _moduleSettings = settings.GetValue(_module);
            }
        }
        base.OnAfterRender(firstRender);
    }

    public void Dispose()
    {

    }
}
